<template>
  <div>
    <el-upload
      ref="upload"
      :action="uploadUrl + action"
      :headers="{ token: token }"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :before-remove="handleBeforeRemove"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :auto-upload="true"
      :limit="20"
      :multiple="false"
      :file-list="fileList"
      :disabled="disabled"
    >
      <el-button slot="trigger" size="small" type="primary">上传</el-button>
    </el-upload>
    <el-dialog
      title="文件上传"
      :visible.sync="dialog"
      width="50%"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      center
    >
      <div style="width: 100%; text-align: center; font-size: 18px">
        <div v-if="loading" style="color: #e6a23c">文件正在上传,请耐心等待</div>
        <div v-if="!loading" style="color: #67c23a">文件上传成功</div>
        <div
          v-loading="loading"
          style="width: 50px; height: 50px; margin: 0 auto"
        ></div>
      </div>
      <span slot="footer">
        <el-button v-if="!loading" type="primary" @click="updateSuccess"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { deleteFiles, getFiles, postBindFiles } from '@/api/System/File';
import axios from 'axios';
export default {
  props: {
    action: {
      type: String,
      default: '/sys-file/upload'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    tableName: {
      type: String,
      default: 'common'
    },
    useType: {
      type: [String, Number],
      default: 'default'
    }
    // pid: {
    //   type: [String, Number],
    //   default: 0,
    // },
  },
  data() {
    return {
      uploadUrl: upload_url,
      // uploadUrl: "http://192.168.3.116:8156",
      token: localStorage.getItem('token'),
      fileList: [],
      loading: false,
      dialog: false,
      pid: this.$store.state.files.currentID || 0
    };
  },
  created() {
    if (this.tableName != '' && this.useType != '' && this.pid != 0) {
      this.selectFiles(this.tableName, this.pid, this.useType).then((res) => {
        if (res && res.length > 0) {
          this.fileList = res;
        }
      });
    }
  },
  methods: {
    handleBeforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`);
      }
    },
    handleRemove(file, fileList) {
      if (file.status == 'ready') {
        return;
      }
      deleteFiles({ id: file.annex_id }).then((res) => {
        if (res.code == 0) {
          this.$message.success('删除成功');
        }
      });
    },
    beforeUpload(file) {
      const isLtM = file.size / 1024 / 1024 < 100;
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/msword' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
        file.type === 'application/vnd.ms-powerpoint' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||
        file.type === 'application/pdf' ||
        file.type === 'video/mp4';

      if (!isImage) {
        this.$message.error('请选择正确的文件格式!');
        return false;
      }
      if (!isLtM) {
        this.$message.error('上传文件大小不能超过 100MB!');
        return false;
      }

      this.loading = true;
      this.dialog = true;

      return isLtM && isImage;
    },
    handleSuccess(res) {
      if (res.code == 0) {
        if (this.pid > 0) {
          // 直接绑定
          let unBind = res.data;
          unBind.table_name = this.tableName;
          unBind.type = this.useType;
          this.bindFile([unBind], this.pid);
        } else {
          // 回传未绑定文件
          const newItem = res.data;
          newItem.table_name = this.tableName;
          newItem.type = this.useType;

          this.$store.commit('files/SET_UNBIND', newItem);
        }
      }
      setTimeout(() => {
        this.loading = false;
      }, 200);
    },
    updateSuccess() {
      this.dialog = false;
    },
    handlePreview(file) {
      if (file && file.response !== undefined) {
        file.url = file.response.data.url;
      }

      axios
        .get(this.uploadUrl + file.url, {
          headers: {
            token: localStorage.getItem('token')
          },
          responseType: 'blob'
        })
        .then((response) => {
          window.open(window.URL.createObjectURL(response), '_blank');
        });
    },
    /** 绑定文件与表
     *  待绑定的数组
     *  待绑定 的 ID
     */
    bindFile(filesArr, id) {
      return new Promise((resolve) => {
        if (id > 0) {
          if (filesArr.length > 0) {
            filesArr = filesArr.map((i) => {
              i.pid = id;
              return i;
            });

            postBindFiles({ files: JSON.stringify(filesArr) })
              .then((res) => {
                if (res.code == 0) {
                  resolve(true);
                } else {
                  resolve(false);
                }
              })
              .catch((err) => {
                resolve(false);
              });
          }
        }
      });
    },
    // 查询绑定的文件
    selectFiles(tableName, pid, type) {
      return new Promise((resolve, reject) => {
        getFiles({
          table_name: tableName,
          pid: pid,
          type: type
        })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    }
  },
  watch: {
    pid(newVal) {}
  }
};
</script>

<style lang="scss" scoped></style>
